package com.diligent.cloud.sfc.factory.impl;

import com.alibaba.fastjson.JSON;
import com.canny.commons.model.Codes;
import com.canny.commons.model.ObjectResult;
import com.canny.commons.model.Result;
import com.canny.commons.page.IPage;
import com.canny.commons.page.Pagination;
import com.diligent.cloud.primary.data.feign.service.mdm.MdmMatTypeFeignService;
import com.diligent.cloud.primary.data.model.mdm.MdmMatType;
import com.diligent.cloud.sfc.factory.StationFactory;
import com.diligent.cloud.sfc.model.MatType;
import com.diligent.cloud.sfc.model.OrderType;
import com.diligent.cloud.sfc.model.detail.FeedPowderDetailInfo;
import com.diligent.cloud.sfc.service.WipService;
import com.diligent.cloud.sfc.util.ConverterUtil;
import com.diligent.cloud.web.model.PageAndCondition;
import com.diligent.cloud.wip.core.vo.StorageLedgerInfo;
import com.diligent.cloud.wip.panel.modle.WipStorageLedger;
import com.diligent.cloud.workorder.enums.WoOrderStatus;
import com.diligent.cloud.workorder.model.WoOrder;
import com.diligent.cloud.workorder.model.WoOrderMatNeed;
import com.diligent.cloud.workorder.service.WoOrderFeignService;
import com.diligent.cloud.workorder.service.WoOrderMatNeedFeignService;
import com.diligent.foundation.data.model.v2.Condition;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * UpPowderStation class
 * 上粉
 *
 * @author xf107278
 * @date 4/2/2020
 */
@Component
public class UpPowderStation implements StationFactory {

    private WipService wipService;

    private final WoOrderFeignService orderFeignService;

    private final WoOrderMatNeedFeignService orderMatNeedFeignService;

    private final MdmMatTypeFeignService matTypeFeignService;


    public UpPowderStation(WipService wipService, WoOrderFeignService orderFeignService, WoOrderMatNeedFeignService orderMatNeedFeignService, MdmMatTypeFeignService matTypeFeignService) {
        this.wipService = wipService;
        this.orderFeignService = orderFeignService;
        this.orderMatNeedFeignService = orderMatNeedFeignService;
        this.matTypeFeignService = matTypeFeignService;
    }

    @Override
    public Result getOrderInfo(WoOrder order) {
        //查当前机台已上架喷涂工单
        FeedPowderDetailInfo feedPowderDetailInfo = new FeedPowderDetailInfo();
        //未完工同色
        int sameOrderNotFinished = (Integer) orderFeignService.selectSameColorWoOrderNum(order.getMachineCode(), order.getColorGroupCode(), WoOrderStatus.schedulings.getStatus(), OrderType.表面处理工单).getBody().getData();
        if (sameOrderNotFinished == 0) {
            feedPowderDetailInfo.setSameOrderNotFinished(sameOrderNotFinished);
        } else {
            feedPowderDetailInfo.setSameOrderNotFinished(sameOrderNotFinished - 1);
        }
        //已完工同色
        feedPowderDetailInfo.setSameOrderFinished((Integer) orderFeignService.selectSameColorWoOrderNum(order.getMachineCode(), order.getColorGroupCode(), WoOrderStatus.finish.getStatus(), OrderType.表面处理工单).getBody().getData());
        //获取当前机台已上架工单
        List<Map> woOrders = (List<Map>) orderFeignService.selectUpWoOrder(order.getMachineCode(), "未上架", OrderType.表面处理工单).getBody().getData();

        Condition condition = new Condition("name", "eq", MatType.粉末, null);
        PageAndCondition pageAndCondition2 = new PageAndCondition();
        pageAndCondition2.setPagination(new Pagination(1L, 1L));
        List<Condition> conditions1 = new ArrayList<>();
        conditions1.add(condition);
        pageAndCondition2.setConditions(conditions1);
        //粉末物料类型
        MdmMatType mdmMatType = matTypeFeignService.selectDataByConditionPage(pageAndCondition2).getBody().getData().getRecords().stream().findFirst().get();


        int projectNum = Integer.parseInt(order.getCv4());

        int modelNum = 0;
        double bmStock = 0;
        double bmStockSameColor = 0;
        double powderStock = 0;
        double powderStockSameColor = 0;
        double bmArea = 0.0;
        double bmWeight = 0.0;
        double powderPlanNum = Double.parseDouble(order.getCv2());
        double powderFinishNum = 0;
        Set<String> modelNumSet = new HashSet();

        //上架工单
        for (Map map : woOrders) {
            WoOrder woOrder = JSON.parseObject(JSON.toJSONString(map), WoOrder.class);
            //项目数
            projectNum += Integer.parseInt(woOrder.getCv4());
            bmArea += Double.parseDouble(woOrder.getCv1()) * Double.parseDouble(woOrder.getCv2());
            bmWeight += Double.parseDouble(woOrder.getCv4()) * Double.parseDouble(woOrder.getCv2());

            powderPlanNum += Integer.parseInt(woOrder.getCv2());
            modelNumSet.add(woOrder.getMatCode());
        }


        PageAndCondition pageAndCondition = new PageAndCondition();
        Pagination pagination = new Pagination(1L, 10000L);
        pageAndCondition.setPagination(pagination);
        List<Condition> conditions = new ArrayList<>();

        List<String> produceDates = new ArrayList<>();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = formatter.format(new Date());

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        Date time = calendar.getTime();
        String yesDate = formatter.format(time);
        produceDates.add(nowDate);
        produceDates.add(yesDate);
        List<Integer> orderStatus = new ArrayList<>();
        orderStatus.add(WoOrderStatus.schedulings.getStatus());
        orderStatus.add(WoOrderStatus.inproduction.getStatus());

        //查当班工单
        Condition machineCondition = new Condition("machineCode", "eq", order.getMachineCode(), null);
        Condition produceDateCondition = new Condition("produceDate", "in", produceDates, null);
        Condition orderTypeCondition = new Condition("orderType", "eq", OrderType.表面处理工单, null);
        Condition orderStatusCondition = new Condition("orderStatus", "in", orderStatus, null);

        conditions.add(machineCondition);
        conditions.add(produceDateCondition);
        conditions.add(orderTypeCondition);
        conditions.add(orderStatusCondition);
        pageAndCondition.setConditions(conditions);
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<WoOrder>>> resultResponseEntity = orderFeignService.page(pageAndCondition);
        List<WoOrder> orders = resultResponseEntity.getBody().getData().getRecords();
        List<StorageLedgerInfo> spakLedgerInfos = new ArrayList<>();
        List<StorageLedgerInfo> ledgerInfos = new ArrayList<>();
        //TODO 优化速度慢问题
        for (WoOrder woOrder : orders) {
            //胚料型号
            String matCode = woOrder.getMatCode();
            //胚料batchCode
            String batchCode = woOrder.getBatchCode();
            StorageLedgerInfo storageLedgerInfo = new StorageLedgerInfo();
            storageLedgerInfo.setMatCode(matCode);
            storageLedgerInfo.setBatchCode(batchCode);
            ledgerInfos.add(storageLedgerInfo);

            //查工单物料需求，粉
            List conditionList = new ArrayList();
            Condition condition1 = new Condition("woOrderId", "eq", woOrder.getId(), null);
            Condition condition2 = new Condition("matType", "eq", mdmMatType.getCode(), null);
            conditionList.add(condition1);
            conditionList.add(condition2);
            PageAndCondition pageAndCondition3 = new PageAndCondition();
            pageAndCondition3.setConditions(conditionList);
            pageAndCondition3.setPagination(new Pagination(1L, 1L));
            WoOrderMatNeed woOrderMatNeed = orderMatNeedFeignService.page(pageAndCondition3).getBody().getData().getRecords().stream().findFirst().get();
            //粉型号
            String matCode1 = woOrderMatNeed.getMatCode();
            //粉BatchCode
            String batchCode1 = woOrderMatNeed.getCv1();

            //粉库存查询实体
            StorageLedgerInfo storageLedgerInfo1 = new StorageLedgerInfo();
            storageLedgerInfo1.setMatCode(matCode1);
            storageLedgerInfo1.setBatchCode(batchCode1);
            spakLedgerInfos.add(storageLedgerInfo1);

            powderStock += Double.parseDouble(woOrder.getCv5());

        }

        feedPowderDetailInfo.setBmArea(bmArea);
        feedPowderDetailInfo.setBmWeight(bmWeight);
        feedPowderDetailInfo.setColorGroup(order.getColorGroupCode());
        feedPowderDetailInfo.setColorDescribe(order.getColorGroupName());
        feedPowderDetailInfo.setProjectNum(projectNum);
        feedPowderDetailInfo.setPowderPlanNum(powderPlanNum);
        feedPowderDetailInfo.setPowderFinishNum(powderFinishNum);

        //上架型号数
        modelNum = modelNumSet.size();
        feedPowderDetailInfo.setModelNum(modelNum);

        WipStorageLedger storageLedger = (WipStorageLedger) wipService.getInventoryByMatCodeAndCwocCodes(order.getWorkCenterCode(), order.getSystemId(), ledgerInfos).getBody().getData();
        if (powderPlanNum != 0) {
            bmStock = storageLedger.getDigit().longValue() / powderPlanNum;
            //胚料备料进度当班
            feedPowderDetailInfo.setBmStock(bmStock);
        } else {
            feedPowderDetailInfo.setBmStock(0.0);
        }

        //查同色工单工单
        Condition sameColorCondition = new Condition("colorGroupCode", "eq", order.getColorGroupCode(), null);
        PageAndCondition pageAndCondition1 = new PageAndCondition();
        pageAndCondition1.setPagination(new Pagination(1L, 10000L));
        conditions.add(sameColorCondition);
        pageAndCondition1.setConditions(conditions);

        //查同色工单工单
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<WoOrder>>> resultResponseEntity1 = orderFeignService.page(pageAndCondition1);
        List<WoOrder> orders1 = resultResponseEntity1.getBody().getData().getRecords();

        List<StorageLedgerInfo> storageLedgerInfos = new ArrayList<>();
        List<StorageLedgerInfo> storageLedgerInfos1 = new ArrayList<>();
        for (WoOrder woOrder : orders1) {
            //查工单物料需求，粉
            List conditionList = new ArrayList();
            Condition condition1 = new Condition("woOrderId", "eq", woOrder.getId(), null);
            Condition condition2 = new Condition("matType", "eq", mdmMatType.getCode(), null);
            conditionList.add(condition1);
            conditionList.add(condition2);
            PageAndCondition pageAndCondition3 = new PageAndCondition();
            pageAndCondition3.setConditions(conditionList);
            pageAndCondition3.setPagination(new Pagination(1L, 1L));
            WoOrderMatNeed woOrderMatNeed = orderMatNeedFeignService.page(pageAndCondition3).getBody().getData().getRecords().stream().findFirst().get();
            //粉型号
            String matCode = woOrderMatNeed.getMatCode();
            //粉BatchCode
            String batchCode = woOrderMatNeed.getCv1();

            //粉库存查询实体
            StorageLedgerInfo storageLedgerInfo = new StorageLedgerInfo();
            storageLedgerInfo.setMatCode(matCode);
            storageLedgerInfo.setBatchCode(batchCode);
            storageLedgerInfos.add(storageLedgerInfo);

            //胚料库存查询实体
            StorageLedgerInfo storageLedgerInfo1 = new StorageLedgerInfo();
            storageLedgerInfo1.setBatchCode(woOrder.getBatchCode());
            storageLedgerInfo1.setMatCode(woOrder.getMatCode());
            storageLedgerInfos1.add(storageLedgerInfo1);
            powderStockSameColor += Double.parseDouble(woOrder.getCv5());

        }
        //查询同色工单胚料库存
        ResponseEntity<ObjectResult> responseEntity = wipService.getInventoryByMatCodeAndCwocCodes(order.getWorkCenterCode(), order.getSystemId(), storageLedgerInfos1);
        WipStorageLedger wipStorageLedger = (WipStorageLedger) responseEntity.getBody().getData();
        BigDecimal bigDecimal = wipStorageLedger.getDigit();

        if (powderPlanNum != 0) {
            //胚料备料进度同色
            bmStockSameColor = bigDecimal.longValue() / powderPlanNum;
            feedPowderDetailInfo.setBmStockSameColor(bmStockSameColor);
        } else {
            feedPowderDetailInfo.setBmStockSameColor(0.0);
        }

        //查询粉末备料进度(当班)
        ResponseEntity<ObjectResult> responseEntity2 = wipService.getInventoryByMatCodeAndCwocCodes(order.getWorkCenterCode(), order.getSystemId(), spakLedgerInfos);
        WipStorageLedger wipStorageLedger2 = (WipStorageLedger) responseEntity2.getBody().getData();
        BigDecimal bigDecima2 = wipStorageLedger2.getDigit();
        if (powderStock == 0) {
            feedPowderDetailInfo.setPowderStock(0.0);
        } else {
            //粉末备料进度同色
            powderStock = bigDecima2.longValue() / powderStock;
            feedPowderDetailInfo.setPowderStock(powderStock);
        }
        //查询同色粉末库存mdmMatType

        ResponseEntity<ObjectResult> responseEntity1 = wipService.getInventoryByMatCodeAndCwocCodes(order.getWorkCenterCode(), order.getSystemId(), storageLedgerInfos);
        WipStorageLedger wipStorageLedger1 = (WipStorageLedger) responseEntity1.getBody().getData();
        BigDecimal bigDecimal1 = wipStorageLedger1.getDigit();
        if (powderStockSameColor == 0) {
            //粉末备料进度同色
            feedPowderDetailInfo.setPowderStockSameColor(0.0);
        } else {
            //粉末备料进度同色
            powderStockSameColor = bigDecimal1.longValue() / powderStockSameColor;
            feedPowderDetailInfo.setPowderStockSameColor(powderStockSameColor);
        }

        return ConverterUtil.ConverterByData(feedPowderDetailInfo, Codes.success.getCode(), Codes.success.getMsg());
    }

    //获取进粉退粉
//    private FeedPowderDetailInfo getOptionCompleteDetail(WoOrder order, FeedPowderDetailInfo feedPowderDetailInfo) {
//        PageAndCondition pageAndCondition =
//                new PageAndCondition();
//        List<Condition> conditions = new ArrayList<>();
//        Pagination pagination = new Pagination(1L, 10L);
//        Condition refCodeCondition = new Condition("refCode", "eq", order.getWoOrder(), null);
//        Condition refRowIdCondition = new Condition("refRowId", "eq", order.getId(), null);
//        conditions.add(refCodeCondition);
//        conditions.add(refRowIdCondition);
//        pageAndCondition.setConditions(conditions);
//        pageAndCondition.setPagination(pagination);
//
//        ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<MfgConsumeDetail>>> consumeDetailResponseEntity =
//                mfgConsumeDetailFeignService.selectDataByConditionPage(pageAndCondition);
//        if (consumeDetailResponseEntity.getBody().getData().getRecords().size() != 0) {
//            MfgConsumeDetail mfgConsumeDetail =
//                    consumeDetailResponseEntity.getBody().getData().getRecords().stream().findFirst().get();
//            feedPowderDetailInfo.setFeedPowderWeight(mfgConsumeDetail.getWeight().longValue());
//            feedPowderDetailInfo.setReturnPowderWeight(mfgConsumeDetail.getReturnWeight().longValue());
//        }
//        return feedPowderDetailInfo;
//    }
}
